﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace pcalc
{
	class RMBString
	{
		double _value;
		string _string;

		public RMBString(double v)
		{
			_value = v;
			_string = GetRmbString(v);
		}

		public double GetValue()
		{
			return _value;
		}

		public override string ToString()
		{
			return _string;
		}

		string[] CN = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };

		string GetRmbString(double v)
		{
			long i = (long)v;
			long f = (long)Math.Round((v - i) * 100);

			string part1 = GetRmbStringPart1(i);
			string part2 = GetRmbStringPart2(f);

			if (f == 0)
				return part1 + "元整";
			else
				return part1 + "元" + part2;
		}

		string GetRmbStringPart2(long fpart)
		{
			fpart = fpart % 100;
			return CN[(fpart / 10)] + "角" + CN[(fpart % 10)] + "分";
		}

		string GetRmbStringPart1(long ipart)
		{
			const int WAN = 10000;
			const int YI = WAN * WAN;

			StringBuilder sb = new StringBuilder();
			long hi, lo;
			string s1, s2;

			if (ipart >= YI)
			{
				hi = ipart / YI;
				lo = ipart % YI;
				s1 = GetRmbStringPart1(hi);
				s2 = (lo != 0 ? GetRmbStringPart1(lo) : "");
				sb.Append(s1 + "亿" + ((lo * 10 > YI || lo == 0) ? "" : CN[0]) + s2);
			}
			else if (ipart >= WAN)
			{
				hi = ipart / WAN;
				lo = ipart % WAN;
				s1 = GetRmbStringPart1(hi);
				s2 = (lo != 0 ? GetRmbStringPart1(lo) : "");
				sb.Append(s1 + "万" + ((lo * 10 > WAN || lo == 0) ? "" : CN[0]) + s2);
			}
			else
			{
				// d:千、c:百、b:十、a:个
				long d, c, b, a;

				a = ipart % 10;
				ipart /= 10;
				b = ipart % 10;
				ipart /= 10;
				c = ipart % 10;
				ipart /= 10;
				d = ipart % 10;

				if (d != 0)
				{
					sb.AppendFormat("{0}{1}", CN[d], "仟");
					if (c == 0 && (b != 0 || a != 0)) sb.Append(CN[0]);
				}

				if (c != 0)
				{
					sb.AppendFormat("{0}{1}", CN[c], "佰");
					if (b == 0 && a != 0) sb.Append(CN[0]);
				}

				if (b != 0)
				{
					sb.AppendFormat("{0}{1}", CN[b], "拾");
				}

				if (a != 0)
				{
					sb.Append(CN[a]);
				}
				else
				{
					if (d == 0 && c == 0 && b == 0) sb.Append(CN[0]);
				}
			}

			return sb.ToString();
		}
	}
}
